/**
 Core script to handle the entire theme and core functions
 **/
var Layout = function () {

	var layoutImgPath = 'layouts/layout4/img/';

	var layoutCssPath = 'layouts/layout4/css/';

	var resBreakpointMd = App.getResponsiveBreakpoint('md');

	var ajaxContentSuccessCallbacks = [];
	var ajaxContentErrorCallbacks = [];

	var getPosTop = function (el) {
		var pos = el.position();
		return pos && pos.top || 0
	}
	var handleSidebarAndContentHeight = function () {
		var dtLayout = $('.dtLayout');
		dtLayout.dtLayout();
		dtLayout.dtLayout("resize");
	};

	// Handle sidebar menu links
	var handleSidebarMenuActiveLink = function (mode, el, $state) {
		var url = location.hash.toLowerCase();
		var menu = $('.page-sidebar-menu');

		if (mode === 'click' || mode === 'set') {
			el = $(el);
		} else if (mode === 'match') {
			menu.find('li > a').each(function () {
				var state = $(this).attr('ui-sref');
				if ($state && state) {
					if ($state.is(state)) {
						el = $(this);
						return;
					}
				} else {
					var path = $(this).attr('href');
					if (path) {
						// url match condition
						path = path.toLowerCase();
						if (path.length > 1 && url.substr(1, path.length - 1) == path.substr(1)) {
							el = $(this);
							return;
						}
					}
				}
			});
		}

		if (!el || el.size() == 0) {
			return;
		}

		if (el.attr('href') == 'javascript:;' ||
			el.attr('ui-sref') == 'javascript:;' ||
			el.attr('href') == '#' ||
			el.attr('ui-sref') == '#'
		) {
			return;
		}

		var slideSpeed = parseInt(menu.data('slide-speed'));
		var keepExpand = menu.data('keep-expanded');

		// begin: handle active state
		if (menu.hasClass('page-sidebar-menu-hover-submenu') === false) {
			menu.find('li.nav-item.open').each(function () {
				var match = false;
				$(this).find('li').each(function () {
					var state = $(this).attr('ui-sref');
					if ($state && state) {
						if ($state.is(state)) {
							match = true;
							return;
						}
					} else if ($(this).find(' > a').attr('href') === el.attr('href')) {
						match = true;
						return;
					}
				});

				if (match === true) {
					return;
				}

				$(this).removeClass('open');
				$(this).find('> a > .arrow.open').removeClass('open');
				$(this).find('> .sub-menu').slideUp();
			});
		} else {
			menu.find('li.open').removeClass('open');
		}

		menu.find('li.active').removeClass('active');
		menu.find('li > a > .selected').remove();
		// end: handle active state

		el.parents('li').each(function () {
			$(this).addClass('active');
			$(this).find('> a > span.arrow').addClass('open');

			if ($(this).parent('ul.page-sidebar-menu').size() === 1) {
				$(this).find('> a').append('<span class="selected"></span>');
			}

			if ($(this).children('ul.sub-menu').size() === 1) {
				$(this).addClass('open');
			}
		});

		if (mode === 'click') {
			if (App.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass('in')) { // close the menu on mobile view while laoding a page
				$('.page-header .responsive-toggler').click();
			}
		}
	};

	// Handle sidebar menu
	var handleSidebarMenu = function () {
		$('.page-sidebar').on('click', 'li > a', function (e) {

			if (App.getViewPort().width >= resBreakpointMd && $(this).parents('.page-sidebar-menu-hover-submenu').size() === 1) { // exit of hover sidebar menu
				return;
			}

			if ($(this).next().hasClass('sub-menu') === false) {
				if (App.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
					$('.page-header .responsive-toggler').click();
				}
				return;
			}

			var parent = $(this).parent().parent();
			var the = $(this);
			var menu = $('.page-sidebar-menu');
			var sub = $(this).next();

			var autoScroll = menu.data("auto-scroll");
			var slideSpeed = parseInt(menu.data("slide-speed"));
			var keepExpand = menu.data("keep-expanded");

			if (keepExpand !== true) {
				parent.children('li.open').children('a').children('.arrow').removeClass('open');
				parent.children('li.open').children('.sub-menu:not(.always-open)').slideUp(slideSpeed);
				parent.children('li.open').removeClass('open');
			}

			var slideOffeset = -200;

			if (sub.is(":visible")) {
				$('.arrow', $(this)).removeClass("open");
				$(this).parent().removeClass("open");
				sub.slideUp(slideSpeed, function () {
					if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
						if ($('body').hasClass('page-sidebar-fixed')) {
							menu.slimScroll({
								'scrollTo': (the.position()).top
							});
						} else {
							App.scrollTo(the, slideOffeset);
						}
					}
					handleSidebarAndContentHeight();
				});
			} else {
				$('.arrow', $(this)).addClass("open");
				$(this).parent().addClass("open");
				sub.slideDown(slideSpeed, function () {
					if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
						if ($('body').hasClass('page-sidebar-fixed')) {
							menu.slimScroll({
								'scrollTo': (the.position()).top
							});
						} else {
							App.scrollTo(the, slideOffeset);
						}
					}
					handleSidebarAndContentHeight();
				});
			}

			e.preventDefault();
		});

		// handle menu close for angularjs version
		if (App.isAngularJsApp()) {
			$(".page-sidebar-menu li > a").on("click", function (e) {
				if (App.getViewPort().width < resBreakpointMd && $(this).next().hasClass('sub-menu') === false) {
					$('.page-header .responsive-toggler').click();
				}
			});
		}

		// handle ajax links within sidebar menu
		$('.page-sidebar').on('click', ' li > a.ajaxify', function (e) {
			e.preventDefault();
			App.scrollTop();

			var url = $(this).attr("href");
			var menuContainer = $('.page-sidebar ul');

			menuContainer.children('li.active').removeClass('active');
			menuContainer.children('arrow.open').removeClass('open');

			$(this).parents('li').each(function () {
				$(this).addClass('active');
				$(this).children('a > span.arrow').addClass('open');
			});
			$(this).parents('li').addClass('active');

			if (App.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
				$('.page-header .responsive-toggler').click();
			}

			Layout.loadAjaxContent(url, $(this));
		});

		// handle ajax link within main content
		$('.page-content').on('click', '.ajaxify', function (e) {
			e.preventDefault();
			App.scrollTop();

			var url = $(this).attr("href");


			App.startPageLoading();

			if (App.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page
				$('.page-header .responsive-toggler').click();
			}

			Layout.loadAjaxContent(url);
		});

		// handle scrolling to top on responsive menu toggler click when header is fixed for mobile view
		$(document).on('click', '.page-header-fixed-mobile .responsive-toggler', function () {
			App.scrollTop();
		});
	};

	var _calculateFixedSidebarViewportHeight = function () {
		var sidebarHeight = App.getViewPort().height - $('.page-header').outerHeight(true);
		if ($('body').hasClass("page-footer-fixed")) {
			sidebarHeight = sidebarHeight - $('.page-footer').outerHeight();
		}

		return sidebarHeight;
	};

	// Handles fixed sidebar
	var handleFixedSidebar = function () {
		var menu = $('.page-sidebar-menu');

		handleSidebarAndContentHeight();

		if ($('.page-sidebar-fixed').size() === 0) {
			return;
		}

		if (App.getViewPort().width >= resBreakpointMd && !$('body').hasClass('page-sidebar-menu-not-fixed')) {
			menu.attr("data-height", _calculateFixedSidebarViewportHeight());
			App.destroySlimScroll(menu);
			App.initSlimScroll(menu);
			handleSidebarAndContentHeight();
		}
	};

	// Handles sidebar toggler to close/hide the sidebar.
	var handleFixedSidebarHoverEffect = function () {
		var body = $('body');
		if (body.hasClass('page-sidebar-fixed')) {
			$('.page-sidebar').on('mouseenter', function () {
				if (body.hasClass('page-sidebar-closed')) {
					$(this).find('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
				}
			}).on('mouseleave', function () {
				if (body.hasClass('page-sidebar-closed')) {
					$(this).find('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
				}
			});
		}
	};

	// Hanles sidebar toggler
	var handleSidebarToggler = function () {
		var body = $('body');

		/**
		 if (Cookies && Cookies.get('sidebar_closed') === '1' && App.getViewPort().width >= resBreakpointMd) {
            $('body').addClass('page-sidebar-closed');
            $('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
        }
		 */

		// handle sidebar show/hide
		$('body').on('click', '.sidebar-toggler', function (e) {
			var sidebar = $('.page-sidebar');
			var sidebarMenu = $('.page-sidebar-menu');
			$(".sidebar-search", sidebar).removeClass("open");

			if (body.hasClass("page-sidebar-closed")) {
				body.removeClass("page-sidebar-closed");
				sidebarMenu.removeClass("page-sidebar-menu-closed");
				if (Cookies) {
					Cookies.set('sidebar_closed', '0');
				}
			} else {
				body.addClass("page-sidebar-closed");
				sidebarMenu.addClass("page-sidebar-menu-closed");
				if (body.hasClass("page-sidebar-fixed")) {
					sidebarMenu.trigger("mouseleave");
				}
				if (Cookies) {
					Cookies.set('sidebar_closed', '1');
				}
			}

			$(window).trigger('resize');
		});

		handleFixedSidebarHoverEffect();

		// handle the search bar close
		$('.page-sidebar').on('click', '.sidebar-search .remove', function (e) {
			e.preventDefault();
			$('.sidebar-search').removeClass("open");
		});

		// handle the search query submit on enter press
		$('.page-sidebar .sidebar-search').on('keypress', 'input.form-control', function (e) {
			if (e.which == 13) {
				$('.sidebar-search').submit();
				return false; //<---- Add this line
			}
		});

		// handle the search submit(for sidebar search and responsive mode of the header search)
		$('.sidebar-search .submit').on('click', function (e) {
			e.preventDefault();
			if ($('body').hasClass("page-sidebar-closed")) {
				if ($('.sidebar-search').hasClass('open') === false) {
					if ($('.page-sidebar-fixed').size() === 1) {
						$('.page-sidebar .sidebar-toggler').click(); //trigger sidebar toggle button
					}
					$('.sidebar-search').addClass("open");
				} else {
					$('.sidebar-search').submit();
				}
			} else {
				$('.sidebar-search').submit();
			}
		});

		// handle close on body click
		if ($('.sidebar-search').size() !== 0) {
			$('.sidebar-search .input-group').on('click', function (e) {
				e.stopPropagation();
			});

			$('body').on('click', function () {
				if ($('.sidebar-search').hasClass('open')) {
					$('.sidebar-search').removeClass("open");
				}
			});
		}
	};
	return {


		setSidebarMenuActiveLink: function (mode, el) {
			handleSidebarMenuActiveLink(mode, el, null);
		},

		setAngularJsSidebarMenuActiveLink: function (mode, el, $state) {
			handleSidebarMenuActiveLink(mode, el, $state);
		},

		initSidebar: function ($state) {
			//layout handlers
			handleFixedSidebar(); // handles fixed sidebar menu
			handleSidebarMenu(); // handles main menu
			handleSidebarToggler(); // handles sidebar hide/show

			App.addResizeHandler(handleFixedSidebar); // reinitialize fixed sidebar on window resize
		},

		initContent: function () {
			return;
		},

		init: function () {
			this.initSidebar(null);
			this.initContent();
		},


		addAjaxContentSuccessCallback: function (callback) {
			ajaxContentSuccessCallbacks.push(callback);
		},

		addAjaxContentErrorCallback: function (callback) {
			ajaxContentErrorCallbacks.push(callback);
		},

		//public function to fix the sidebar and content height accordingly
		fixContentHeight: function () {
			return;
		},

		initFixedSidebarHoverEffect: function () {
			handleFixedSidebarHoverEffect();
		},

		initFixedSidebar: function () {
			handleFixedSidebar();
		},

		getLayoutImgPath: function () {
			return App.getAssetsPath() + layoutImgPath;
		},

		getLayoutCssPath: function () {
			return App.getAssetsPath() + layoutCssPath;
		}
	};

}();

if (App.isAngularJsApp() === false) {
	jQuery(document).ready(function () {
		Layout.init(); // init metronic core componets
	});
}